package com.recyclerviewdemo;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.MenuItem;
import android.widget.Toast;

import com.recyclerviewdemo.Listener.RecyclerViewClickListener;
import com.recyclerviewdemo.Services.NetWork;
import com.recyclerviewdemo.adapters.RecyclerviewAdapter;
import com.recyclerviewdemo.entity.GankResult;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;

import java.util.List;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func2;
import rx.schedulers.Schedulers;

public class GankActivity extends RxAppCompatActivity {


    private RecyclerView recycler_view;
    private SwipeRefreshLayout swipe;
    private int contentQuantity = 20;
    private List<GankResult.ResultsBean> picData;
    private RecyclerviewAdapter mAdapter;
    private boolean mIsFirstTimeTouchBottom = true;
    private StaggeredGridLayoutManager layoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gank);

        initView();
        initData();
    }


    private void initView(){
        recycler_view = (RecyclerView)findViewById(R.id.recycler_view);
        swipe = (SwipeRefreshLayout)findViewById(R.id.swipe);
    }

    private void initData() {

        try {
            layoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
            mAdapter = new RecyclerviewAdapter(GankActivity.this);

            recycler_view.setAdapter(mAdapter);
            recycler_view.setLayoutManager(layoutManager);
            recycler_view.addOnScrollListener(getOnBottomListener(layoutManager));

            getNetData(false); //刚进入界面先刷新一次

            //调用RecyclerView#addOnItemTouchListener方法能添加一个RecyclerView.OnItemTouchListener对象
            recycler_view.addOnItemTouchListener(new RecyclerViewClickListener(this, new RecyclerViewClickListener.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    Toast.makeText(GankActivity.this, "Click " + picData.get(position).getDesc(), Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onItemLongClick(View view, int position) {
                    Toast.makeText(GankActivity.this, "Long Click " + picData.get(position).getWho(), Toast.LENGTH_SHORT).show();
                }
            }));

            //刷新时执行的事件
            swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    getNetData(true);
                }
            });

        }catch (Exception e){
            Log.e("=====>initview",e.toString());
        }
    }


    //查询最后一个可见Item的下标
    public int findLastVisibleItemPosition() {
        int lastVisibleItemPosition = 0;
        lastVisibleItemPosition = layoutManager.getItemCount()-1;
        return lastVisibleItemPosition;
    }

    //刷新获取网络数据
    private void getNetData(boolean loadMore) {
        try {
            swipe.measure(View.MEASURED_SIZE_MASK, View.MEASURED_HEIGHT_STATE_SHIFT);
            swipe.setRefreshing(true);

            if (loadMore) contentQuantity = contentQuantity + 10;
            Observable.combineLatest(NetWork.getGankApi().getAllDate("福利", contentQuantity, 1), NetWork.getGankApi().getAllDate("休息视频", contentQuantity, 1),
                    new Func2<GankResult, GankResult, Void>() {
                        @Override
                        public Void call(GankResult PicResult, GankResult TextResult) {
                            picData = PicResult.getResults();
                            mAdapter.setPicData(PicResult.getResults());
                            mAdapter.setTextData(TextResult.getResults());
                            return null;
                        }
                    })

                    .compose(this.<Void>bindToLifecycle())
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<Void>() {
                        @Override
                        public void call(Void aVoid) {
                            mAdapter.notifyDataSetChanged();
                            swipe.setRefreshing(false);
                        }
                    });
        }catch (Exception e){
            Log.e("---->getdata",e.toString());
        }
    }

    RecyclerView.OnScrollListener getOnBottomListener(final StaggeredGridLayoutManager layoutManager) {
        return new RecyclerView.OnScrollListener() {
            @Override public void onScrolled(RecyclerView rv, int dx, int dy) {
                boolean isBottom =
                        layoutManager.findLastCompletelyVisibleItemPositions(new int[2])[1] >=
                                mAdapter.getItemCount() - 20;
                if (!swipe.isRefreshing() && isBottom) {
                    if (!mIsFirstTimeTouchBottom) {
                        swipe.setRefreshing(true);
                        getNetData(true);
                    } else {
                        mIsFirstTimeTouchBottom = false;
                    }
                }
            }
        };
//    RecyclerView.OnScrollListener getOnBottomListener(final StaggeredGridLayoutManager layoutManager) {
//        return new RecyclerView.OnScrollListener() {
//
//            int lastVisibleItem;
//            @Override
//            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == layoutManager.getItemCount()) {
//                    getNetData(true);
//                }
//                swipe.setRefreshing(false);
//            }
//
//
//            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//                lastVisibleItem = findLastVisibleItemPosition();
//                swipe.setRefreshing(false);
//            }
//        };
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
